<?php

namespace app\admin\controller;

use app\admin\business\CashBus;
use app\admin\business\OrdersBus;
use app\admin\model\Config as ConfigModel;
use app\admin\model\Goods as goodsModel;
use app\admin\model\OrdersGoods;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\db\Where;
use think\facade\Db;
use think\facade\Request;
use think\facade\View;

class Cash extends Common
{

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 订单列表
     * @author lijia
     * @date 2019-08-08
     */
    public function index()
    {
        if (Request::isPost()) {
            $key = input('post.key');
            $status = input('post.status',0,'intval');
            $start_time = input('post.start_time');
            $end_time = input('post.end_time');
            $page = input('page') ? input('page') : 1;
            $pageSize = input('limit') ? input('limit') : config('pageSize');
            $sort_by = input('sort_by') ? input('sort_by') : 'id';
            $sort_order = input('sort_order') ? input('sort_order') : 'desc';
            $where = [];
            if ($key) {
                $where[] = ['b.username|b.mobile', 'like', "%" . $key . "%"];
            }
            if ($start_time){
                $where[] = ['a.create_time','>',$start_time];
            }
            if ($end_time){
                $where[] = ['a.create_time','<',$end_time];
            }
            if ($status) {
                $where[] = ['a.status', '=', $status];
            }
            $list = CashBus::getList($where,$sort_by,$sort_order,$pageSize,$page);
            return $result = ['code' => 0, 'msg' => '获取成功!', 'data' => $list['data'], 'count' => $list['total'], 'rel' => 1];
        }
        return View::fetch();
    }

    /**
     * 导出提现
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function exportExcel(){
        $key = input('get.key');
        $status = input('get.status',0,'intval');
        $start_time = input('get.start_time');
        $end_time = input('get.end_time');
        $where = [];
        if ($key) {
            $where[] = ['b.username|b.mobile', 'like', "%" . $key . "%"];
        }
        if ($start_time){
            $where[] = ['a.create_time','>',$start_time];
        }
        if ($end_time){
            $where[] = ['a.create_time','<',$end_time];
        }
        if ($status) {
            $where[] = ['a.status', '=', $status];
        }
        $list = Db::name('cash')->alias('a')
            ->join('user b','b.user_id = a.user_id','left')
            ->where($where)
            ->field('a.*,b.username,b.mobile')
            ->select()
            ->toArray();
        foreach ($list as $k => $v){
            if ($v['type'] == 1){
                $list[$k]['type'] = '支付宝';
            }else{
                $list[$k]['type'] = '银行卡';
            }
            if ($v['status'] == 1){
                $list[$k]['status'] = '申请中';
            }else if($v['status'] == 2){
                $list[$k]['status'] = '已通过';
            }else{
                $list[$k]['status'] = '已驳回';
            }
            $list[$k]['sj_amount'] = $v['amount']*0.8;
        }
        $spreadsheet = new Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet();
        //设置工作表标题名称
        $worksheet->setTitle('提现列表');
        $worksheet->calculateColumnWidths();
        // 设置列的宽度
        $spreadsheet->getActiveSheet()->getDefaultColumnDimension()->setWidth(20);
        $spreadsheet->getActiveSheet()->getColumnDimension('I')->setWidth(35);
        //设置单元格内容
        $worksheet->setCellValueByColumnAndRow(1, 1, '提现列表');
        $worksheet->setCellValueByColumnAndRow(1, 2, 'ID');
        $worksheet->setCellValueByColumnAndRow(2, 2, '提现用户');
        $worksheet->setCellValueByColumnAndRow(3, 2, '用户电话');
        $worksheet->setCellValueByColumnAndRow(4, 2, '提现金额');
        $worksheet->setCellValueByColumnAndRow(5, 2, '手续费');
        $worksheet->setCellValueByColumnAndRow(6, 2, '账户类型');
        $worksheet->setCellValueByColumnAndRow(7, 2, '银行名称');
        $worksheet->setCellValueByColumnAndRow(8, 2, '账户名称');
        $worksheet->setCellValueByColumnAndRow(9, 2, '账户号码');
        $worksheet->setCellValueByColumnAndRow(10, 2, '实际转账');
        $worksheet->setCellValueByColumnAndRow(11, 2, '状态');
        $worksheet->setCellValueByColumnAndRow(12, 2, '发起时间');
        //合并单元格
        $worksheet->mergeCells('A1:L1');
        $styleArray = [
            'font' => [
                'bold' => true
            ],
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
            ],
        ];
        //设置单元格样式
        $worksheet->getStyle('A1')->applyFromArray($styleArray)->getFont()->setSize(14);
        $worksheet->getStyle('A2:L2')->applyFromArray($styleArray)->getFont()->setSize(10);
        $len = count($list);
        for ($i=0; $i < $len; $i++) {
            $j = $i + 3; //从表格第3行开始
            $worksheet->setCellValueByColumnAndRow(1, $j, $list[$i]['id']);
            $worksheet->setCellValueByColumnAndRow(2, $j, $list[$i]['username']);
            $worksheet->setCellValueByColumnAndRow(3, $j, $list[$i]['mobile']);
            $worksheet->setCellValueByColumnAndRow(4, $j, $list[$i]['amount']);
            $worksheet->setCellValueByColumnAndRow(5, $j, $list[$i]['service_price']);
            $worksheet->setCellValueByColumnAndRow(6, $j, $list[$i]['type']);
            $worksheet->setCellValueByColumnAndRow(7, $j, $list[$i]['bank_name']);
            $worksheet->setCellValueByColumnAndRow(8, $j, $list[$i]['account_name']);
            $worksheet->setCellValueByColumnAndRow(9, $j, ' '.$list[$i]['account']);
            $worksheet->setCellValueByColumnAndRow(10, $j, $list[$i]['sj_amount']);
            $worksheet->setCellValueByColumnAndRow(11, $j, $list[$i]['status']);
            $worksheet->setCellValueByColumnAndRow(12, $j, $list[$i]['create_time']);
        }
        $styleArrayBody = [
            'borders' => [
                'allBorders' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
                    'color' => ['argb' => '666666'],
                ],
            ],
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
            ],
        ];
        $total_jzInfo = $len + 2;
        //添加所有边框/居中
        $worksheet->getStyle('A1:L'.$total_jzInfo)->applyFromArray($styleArrayBody);
        $filename = '提现列表.xlsx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Cache-Control: max-age=0');
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
    }

    /**
     * 删除
     * @return Array|array
     */
    public function doDelete()
    {
        try {
            $id = input('request.id');
            if (!$id) {
                return ['code' => 3000, 'msg' => '请选择要删除的数据!'];
            }
            $result = Db::name('cash')->where("id", $id)->delete();
            if ($result) {
                return ['code' => 0, 'msg' => '操作成功!'];
            }
            return ['code' => 3000, 'msg' => '操作失败!'];
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }



    /**
     * 通过提现，送积分
     * @return Array|array
     */
    public function confirm()
    {
        Db::startTrans();
        try {
            $id = input('request.id');
            if (!$id) {
                return ['code' => 3000, 'msg' => '操作失败!'];
            }
            $cash = Db::name('cash')->where('id',$id)->find();
            // 返回提现金额
            Db::name('user')->where('user_id',$cash['user_id'])->inc('integral',$cash['integral'])->update();
            // 修改提现信息
            Db::name('cash')->where("id", $id)->update(['status' => 2]);
            Db::commit();
            return ['code' => 0, 'msg' => '操作成功!'];
        } catch (\Exception $e) {
            Db::rollback();
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }


    /**
     * 驳回提现
     * @return array
     */
    public function cancelReturn()
    {
        Db::startTrans();
        try {
            $id = input('request.id');
            $remarks = input('request.remarks');
            if (!$id) {
                return ['code' => 3000, 'msg' => '操作失败!'];
            }
            $cash = Db::name('cash')->where('id',$id)->find();
            // 返回提现金额
            Db::name('user')->where('user_id',$cash['user_id'])->inc('money',$cash['amount'])->update();
            // 修改提现信息
            Db::name('cash')->where("id", $id)->update(['status' => 3,'remarks' => $remarks]);
            Db::commit();
            return ['code' => 0, 'msg' => '操作成功!'];
        } catch (\Exception $e) {
            Db::rollback();
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }


}